package com.Humanities.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {

    @Value("${elasticsearch.hostlist}")
    private String hostlist;

    @Bean
public RestHighLevelClient restHighLevelClient(){
    // 解析 `hostlist` 配置信息，将其按逗号分割为多个主机地址
    String[] split = hostlist.split(",");
    // 创建 HttpHost 数组，用于存放 Elasticsearch 主机和端口的配置信息
    HttpHost[] httpHostArray = new HttpHost[split.length];
    for(int i=0;i<split.length;i++){
        // 获取每个主机地址
        String item = split[i];
        // 将主机地址解析为 HttpHost 对象，包含主机名、端口号和协议类型
        httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
    }
    // 创建并返回 RestHighLevelClient 客户端实例
    return new RestHighLevelClient(RestClient.builder(httpHostArray));
}
}